package cn.ug.mall.web.controller;

import cn.ug.aop.RequiresPermissions;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.login.LoginHelper;
import cn.ug.feign.MemberAddressService;
import cn.ug.mall.bean.*;
import cn.ug.mall.mapper.entity.MallGoodsOrder;
import cn.ug.mall.service.LogisticsService;
import cn.ug.mall.service.MallGoodsOrderService;
import cn.ug.mall.service.MallGoodsService;
import cn.ug.member.bean.response.MemberAddressBaseBean;
import cn.ug.util.PaginationUtil;
import cn.ug.util.SerialNumberWorker;
import cn.ug.util.UF;
import cn.ug.web.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import static cn.ug.util.ConstantUtil.MINUS;

@RestController
@RequestMapping("order")
public class MallGoodsOrderController extends BaseController {
	@Autowired
	private MallGoodsOrderService mallGoodsOrderService;
	@Autowired
    private LogisticsService logisticsService;
	@Autowired
    private MallGoodsService mallGoodsService;
	@Autowired
    private MemberAddressService memberAddressService;

    @GetMapping("/member/list")
    public SerializeObject<DataTable<MemberGoodsOrderBean>> list(@RequestHeader String accessToken, Page page, Integer status) {
        status = status == null ? 0 : status;
        String memberId = LoginHelper.getLoginId();
		if(StringUtils.isBlank(memberId)) {
			return new SerializeObjectError<>("00000102");
		}
        int total = mallGoodsOrderService.countRecords(memberId, status);
        page.setTotal(total);
        if (total > 0) {
            List<MemberGoodsOrderBean> list = mallGoodsOrderService.listRecords(memberId, status, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberGoodsOrderBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberGoodsOrderBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<MemberGoodsOrderBean>()));
    }

    @GetMapping("/detail")
    public SerializeObject<MemberGoodsOrderDetailBean> getDetail(@RequestHeader String accessToken, String orderNO) {
        orderNO = UF.toString(orderNO);
        if (StringUtils.isBlank(orderNO)) {
            return new SerializeObjectError<>("00000002");
        }
        String memberId = LoginHelper.getLoginId();
        if(StringUtils.isBlank(memberId)) {
            return new SerializeObjectError<>("00000102");
        }
        MemberGoodsOrderDetailBean bean = mallGoodsOrderService.getOrderDetail(orderNO);
        if (bean != null && bean.getStatus() == 2) {
            bean.setStatus(3);
        }
        SerializeObject<MemberAddressBaseBean> addressBean = memberAddressService.findByMemberId(memberId);
        if (addressBean != null && addressBean.getData() != null) {
            MemberAddressBaseBean addressBaseBean = addressBean.getData();
            bean.setName(addressBaseBean.getName());
            bean.setMobile(addressBaseBean.getMobile());
            bean.setAddress(addressBaseBean.getProvinceName()+MINUS+addressBaseBean.getCityName()+MINUS+addressBaseBean.getAreaName()+MINUS+addressBaseBean.getAddress());
        }
        if (bean != null && StringUtils.isBlank(bean.getCompany())) {
            bean.setCompany("准备发货，暂无信息");
        }
        if (bean != null && StringUtils.isBlank(bean.getSerialNO())) {
            bean.setSerialNO("准备发货，暂无信息");
        }
        if (bean != null && StringUtils.isBlank(bean.getPhone())) {
            bean.setPhone("准备发货，暂无信息");
        }
        return new SerializeObject<>(ResultType.NORMAL, bean);
    }

    /**
     *  申请支付
     * @param accessToken
     * @param goodsId 商品的id
     * @param source 订单来源 1：IOS 2：H5 3：微信小程序 4：第三方平台;5:安卓
     * @return
     */
    @PostMapping("/pay")
    public SerializeObject payOrder(@RequestHeader String accessToken, String goodsId, Integer source) {
        goodsId = UF.toString(goodsId);
        if (StringUtils.isBlank(goodsId)) {
            return new SerializeObjectError<>("00000002");
        }
        if (source == null) {
            return new SerializeObjectError<>("00000002");
        }
        MallGoodsBean goods = mallGoodsService.findById(goodsId);
        if (goods == null) {
            return new SerializeObjectError<>("23000005");
        }
        if (goods.getStock() < 1) {
            return new SerializeObjectError<>("23000006");
        }
        String memberId = LoginHelper.getLoginId();
        if(StringUtils.isBlank(memberId)) {
            return new SerializeObjectError<>("00000102");
        }
        MallGoodsOrder order = new MallGoodsOrder();
        order.setSource(source);
        order.setMemberId(memberId);
        order.setGoodsId(goods.getId());
        order.setGoodsName(goods.getName());
        order.setPrice(goods.getPrice());
        order.setFare(goods.getFare());
        order.setProcessingFee(goods.getProcessingFee());
        order.setActualAmount(goods.getPrice().add(goods.getFare()).add(goods.getProcessingFee()));
        order.setQuantity(1);
        String orderNO = SerialNumberWorker.getInstance().nextId();
        order.setOrderNO(orderNO);
        if (mallGoodsOrderService.addOrder(order)) {
            return new SerializeObject(ResultType.NORMAL, "00000001", orderNO);
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @GetMapping("/info")
    public SerializeObject<MemberGoodsOrderDetailBean> getOrderDetail(String orderNO) {
        orderNO = UF.toString(orderNO);
        if (StringUtils.isBlank(orderNO)) {
            return new SerializeObjectError<>("00000002");
        }
        return new SerializeObject<>(ResultType.NORMAL, mallGoodsOrderService.getOrderDetail(orderNO));
    }

    @PostMapping("/succeed")
    public SerializeObject succeedOrder(String orderNO) {
        orderNO = UF.toString(orderNO);
        if (StringUtils.isBlank(orderNO)) {
            return new SerializeObjectError<>("00000002");
        }
        if (mallGoodsOrderService.succeedGoodsOrder(orderNO)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PostMapping("/fail")
    public SerializeObject failOrder(String orderNO, String reason) {
        orderNO = UF.toString(orderNO);
        reason = UF.toString(reason);
        if (StringUtils.isBlank(orderNO)) {
            return new SerializeObjectError<>("00000002");
        }
        if (mallGoodsOrderService.failGoodsOrder(orderNO, reason)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PostMapping("/shipment")
    public SerializeObject<MemberGoodsOrderDetailBean> shipment(String orderNO, String serialNo, String company,String phone) {
        orderNO = UF.toString(orderNO);
        serialNo = UF.toString(serialNo);
        company = UF.toString(company);
        phone = UF.toString(phone);
        if (StringUtils.isBlank(orderNO)) {
            return new SerializeObjectError<>("00000002");
        }
        if (StringUtils.isBlank(serialNo)) {
            return new SerializeObjectError<>("23000003");
        }
        if (StringUtils.isBlank(company)) {
            return new SerializeObjectError<>("23000004");
        }
        LogisticsBean bean = new LogisticsBean();
        bean.setOrderNo(orderNO);
        bean.setSerialNo(serialNo);
        bean.setCompany(company);
        bean.setPhone(phone);
        logisticsService.save(bean);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    @PostMapping("/receive")
    public SerializeObject<MemberGoodsOrderDetailBean> receive(String orderNO) {
        orderNO = UF.toString(orderNO);
        if (StringUtils.isBlank(orderNO)) {
            return new SerializeObjectError<>("00000002");
        }
        logisticsService.receive(orderNO);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    @PostMapping("/add/remark")
    public SerializeObject<MemberGoodsOrderDetailBean> addRemark(String orderNO, String remark) {
        orderNO = UF.toString(orderNO);
        remark = UF.toString(remark);
        if (StringUtils.isBlank(orderNO)) {
            return new SerializeObjectError<>("00000002");
        }
        if (StringUtils.isBlank(remark)) {
            return new SerializeObjectError<>("23000002");
        }
        if (mallGoodsOrderService.addRemark(orderNO, remark)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @RequiresPermissions("mall:order")
    @GetMapping(value = "/list")
    public SerializeObject<DataTable<GoodsOrderBean>> list(@RequestHeader String accessToken, Page page, Integer status, String orderNO, String userName, String userMobile, String goodsName,
                                                           String startDate, String endDate) {
        status = status == null ? 0 : status;
        orderNO = UF.toString(orderNO);
        userName = UF.toString(userName);
        userMobile = UF.toString(userMobile);
        goodsName = UF.toString(goodsName);
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        int total = mallGoodsOrderService.countOrders(status, orderNO, userName, userMobile, goodsName, startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            List<GoodsOrderBean> list = mallGoodsOrderService.listOrders(status, orderNO, userName, userMobile, goodsName, startDate, endDate,
                    PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<GoodsOrderBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<GoodsOrderBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<GoodsOrderBean>()));
    }
}